package com.chisheng.student.servlet;

import com.chisheng.common.Page;
import com.chisheng.student.Student;
import com.chisheng.service.impl.StudentServiceImpl;
import com.chisheng.student.StudentUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Objects;

/**
 * 添加学生请求处理
 *
 * @author chisheng
 * @since 2021-11-05
 */
@WebServlet("/add")
public class AddServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 学生参数封装
        Student student = StudentUtils.populateStudent(request.getParameterMap());
        if (student != null) {
            // 添加学生
            StudentServiceImpl studentService = new StudentServiceImpl();
            boolean result = studentService.add(student);
            if (result) {
                request.setAttribute("status", true);
                request.setAttribute("message", "添加成功");
            } else {
                request.setAttribute("status", false);
                request.setAttribute("message", "添加失败");
            }
        } else {
            request.setAttribute("status", false);
            request.setAttribute("message", "请求参数错误");
        }

        // 请求转发
        String url = String.format("/page?current=%d&size=%d", 1, 12);
        RequestDispatcher dispatcher = request.getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}
